#include <constants.h>
#include <dblib.h>
#include <params.h>
#include <stdafx.h>
#include <celko.h>
#include <stdexcept>

#ifdef __cplusplus
extern "C" {
#endif

RETCODE __declspec(dllexport) xp_phon_celko(SRV_PROC *srvproc);

#ifdef __cplusplus
}
#endif

RETCODE __declspec(dllexport) xp_phon_celko(SRV_PROC *srvproc) {
	params *p1 = new params();
	params *p2 = new params();
	RETCODE rc = XP_NOERROR;
	int numparams = params::getparamcount(srvproc);
	Celko c;
	try
	{
		if (numparams != 2) {
			Dblib::printerror(srvproc, USAGE_CELKO);
			rc = XP_ERROR;
		}
		if (rc == XP_NOERROR) {
			params::getparam(srvproc, 1, p1);
			params::getparam(srvproc, 2, p2);
			if (p1->isoutput || !p2->isoutput) {
				Dblib::printerror(srvproc, USAGE_CELKO);
				rc = XP_ERROR;
			}
		}
		if (rc == XP_NOERROR) {
			c.Encode(p1->cdata, p1->length);
		}
	} catch (std::exception ex) {
		Dblib::printerror(srvproc, ERR_CELKO_EXCEPTION);
		rc = XP_ERROR;
	}
	if (rc == XP_NOERROR) {
		srv_paramsetoutput(srvproc, 2, c.Result, 8, FALSE);
	} else {
		srv_paramsetoutput(srvproc, 2, (BYTE *)"", 0, TRUE);
	}
  
	// Now return the number of rows processed
	srv_senddone(srvproc, SRV_DONE_MORE, (DBUSMALLINT)0, (DBINT)0);

	if (p1 != NULL)
		delete p1;
	p1 = NULL;
	if (p2 != NULL)
		delete p2;
	p2 = NULL;
	return rc;
}